﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using WeSSysUser.util;
using WeSSysUser.model;

namespace WeSSysUser.controller
{
    public class SysUserController
    {
        public static DataTable getUserById(int id)
        {
            //get
            try
            {
                object[,] parameters = { { "@id", id } };
                return DB.getData("select * from SYSUSER where id=@id", parameters);
            }
            catch (Exception ex)
            {
                // log
                //LogController.createLog(new Log(DateTime.Now.ToString("yyyyMMddHHmmss"), ex.Message, 1, "Error getUserById"));
                return null;
            }
        }

        public static string createUserForActivating(string email, string password)
        {
            //get
            try
            {
                string hashPassword = Common.generateHash(password);
                string activatedToken = Common.generateHash(email);
                object[,] parameters = {{"@email", email }, 
                                        {"@password", hashPassword },
                                        {"@registeredDate", DateTime.Now.ToString("yyyyMMddHHmmss")},
                                        {"@activatedToken", activatedToken}};
                bool result = DB.exec("insert into SysUser(email, password, registeredDate, activatedToken) " +
                    "values (@email, @password, @registeredDate, @activatedToken);", parameters);

                if (result)
                    return DB.getValue("select IDENT_CURRENT('SYSUSER');");
                else
                    return "";
            }
            catch (Exception ex)
            {
                // log
                //LogController.createLog(new Log(DateTime.Now.ToString("yyyyMMddHHmmss"), ex.Message, 1, "Error createUserForActivating"));
                return "";
            }
        }

        public static ResetActivatedTokenResult resetActivatedToken(string email, string randomString)
        {
            //get
            try
            {
                DataTable dt = SysUserController.getUserByEmail(email);
                if (dt != null && dt.Rows.Count > 0)
                {
                    if (dt.Rows[0]["ActivatedDate"] != null && dt.Rows[0]["ActivatedDate"].ToString() != "")
                        return new ResetActivatedTokenResult{
                            sysUserResultStatus = new SysUserResultStatus {
                            statusCode =  ResetActivatedTokenResult.STATUS_ALREADY_ACTIVATED_USER_CODE,
                            statusText = ResetActivatedTokenResult.STATUS_ALREADY_ACTIVATED_USER_TEXT
                            },
                            token = ""
                        };

                    string resetActivatedToken = Common.generateHash(email + randomString);
                    object[,] parameters = {{"@email", email }, 
                                        {"@registeredDate", DateTime.Now.ToString("yyyyMMddHHmmss")},
                                        {"@activatedToken", resetActivatedToken}};
                    DB.exec("update SysUser set registeredDate = @registeredDate, activatedToken = @activatedToken " +
                        "where email = @email;", parameters);

                    return new ResetActivatedTokenResult
                    {
                        sysUserResultStatus = new SysUserResultStatus
                        {
                            statusCode = ResetActivatedTokenResult.STATUS_VALID_RESET_CODE,
                            statusText = ResetActivatedTokenResult.STATUS_VALID_RESET_TEXT
                        },
                        token = resetActivatedToken
                    };
                }
                else
                {
                    return new ResetActivatedTokenResult
                    {
                        sysUserResultStatus = new SysUserResultStatus
                        {
                            statusCode = ResetActivatedTokenResult.STATUS_GENERAL_ERROR_CODE,
                            statusText = ResetActivatedTokenResult.STATUS_GENERAL_ERROR_TEXT
                        },
                        token = ""
                    };
                }


            }
            catch (Exception ex)
            {
                // log
                //LogController.createLog(new Log(DateTime.Now.ToString("yyyyMMddHHmmss"), ex.Message, 1, "Error resetActivatedToken"));
                return new ResetActivatedTokenResult
                {
                    sysUserResultStatus = new SysUserResultStatus
                    {
                        statusCode = ResetActivatedTokenResult.STATUS_GENERAL_ERROR_CODE,
                        statusText = ResetActivatedTokenResult.STATUS_GENERAL_ERROR_TEXT
                    },
                    token = ""
                };
            }
        }

        public static ResetPasswordResult resetPassword(string email)
        {
            //get
            try
            {
                DataTable dt = SysUserController.getUserByEmail(email);
                if (dt != null && dt.Rows.Count > 0)
                {
                    string newPass = Common.getRandomString(8);
                    object[,] parameters = { { "@Id", dt.Rows[0]["Id"].ToString() },
                                             { "@Password", Common.generateHash(newPass)}};
                    bool rs =  DB.exec("update SysUser set Password = @Password where Id = @Id;", parameters);

                    if (rs)
                    {
                        return new ResetPasswordResult
                        {
                            sysUserResultStatus = new SysUserResultStatus
                            {
                                statusCode = ResetPasswordResult.STATUS_VALID_RESET_CODE,
                                statusText = ResetPasswordResult.STATUS_VALID_RESET_TEXT
                            },
                            password = newPass
                        };
                    }
                    else
                    {
                        return new ResetPasswordResult
                        {
                            sysUserResultStatus = new SysUserResultStatus
                            {
                                statusCode = ResetPasswordResult.STATUS_GENERAL_ERROR_CODE,
                                statusText = ResetPasswordResult.STATUS_GENERAL_ERROR_TEXT
                            },
                            password = ""
                        };
                    }
                }
                else
                {
                    return new ResetPasswordResult
                    {
                        sysUserResultStatus = new SysUserResultStatus
                        {
                            statusCode = ResetPasswordResult.STATUS_GENERAL_ERROR_CODE,
                            statusText = ResetPasswordResult.STATUS_GENERAL_ERROR_TEXT
                        },
                        password = ""
                    };
                }


            }
            catch (Exception ex)
            {
                // log
                //LogController.createLog(new Log(DateTime.Now.ToString("yyyyMMddHHmmss"), ex.Message, 1, "Error resetActivatedToken"));
                return new ResetPasswordResult
                {
                    sysUserResultStatus = new SysUserResultStatus
                    {
                        statusCode = ResetPasswordResult.STATUS_GENERAL_ERROR_CODE,
                        statusText = ResetPasswordResult.STATUS_GENERAL_ERROR_TEXT
                    },
                    password = ""
                };
            }
        }

        private static DataTable getUserByEmail(string email)
        {
            //get
            try
            {
                object[,] parameters = { { "@email", email } };
                return DB.getData("select * from SYSUSER where email=@email", parameters);
            }
            catch (Exception ex)
            {
                // log
                //LogController.createLog(new Log(DateTime.Now.ToString("yyyyMMddHHmmss"), ex.Message, 1, "Error getUserByEmail"));
                return null;
            }
        }
    
    }
}